package com.dailyblue.java;

import lombok.SneakyThrows;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Scanner;

// 字节缓冲流
public class DemoE {

    private static Scanner scan = new Scanner(System.in);

    // 不带缓冲
    @SneakyThrows
    private static void a() {
        File file = new File("/Users/dailyblue/a/a.txt");
        OutputStream out = new FileOutputStream(file, true);
        while (true) {
            System.out.print("Input:");
            String message = scan.next();
            if ("exit".equals(message)) {
                break;
            }
            byte[] bytes = (message + "\n").getBytes();
            // 每次执行都实际的写入到了硬盘中
            out.write(bytes);
        }
    }

    // 有缓冲区的效果
    @SneakyThrows
    private static void b() {
        File file = new File("/Users/dailyblue/a/a.txt");
        OutputStream out = new FileOutputStream(file, true);
        BufferedOutputStream bos = new BufferedOutputStream(out);
        while (true) {
            System.out.print("Input:");
            String message = scan.next();
            if ("exit".equals(message)) {
                break;
            }
            byte[] bytes = (message + "\n").getBytes();
            // 每次执行都写入到缓冲区中
            bos.write(bytes);
        }
        // 通过刷新缓冲区来实际写入到硬盘中
        bos.flush();
        bos.close(); // 自带一次刷新
    }

    public static void main(String[] args) {
        b();
    }
}
